define(function (require) {
    require('bootstrapValidator');
    require('messager');
    require('table');
    require('typeahead');
    require('doctor-data');
    require('fileinput');
    require('daterangepicker');
    require('doctor-select');
    require('moment');
    require('clockpicker');
    require('datetimepicker');
    require('iCheck');

    $.module("DATA.productprize", function () {

        return {
            init: function () {
                this.loadData();
                this.loadEvent();
            },
            clearDatas:function () {
                var that = this;

                $("#_id").val(0);
                $("#productname").val('');
                $("#productenname").val('');

                $("#hide_img").val('');
                $("#pic").fileinput('clear').fileinput('destroy');

                $("#havenum").val(0);
                $("#sendnum").val(0);
                $("#adddate").val(0);

                $("#sortnum").val(0);

                $('#fm').bootstrapValidator('resetForm', true);
                that.showDiv('main_div');
            },
            loadData: function (pageNumber, pageSize) {
                var that = this;

                var s_id = $("#s_id").val();
                var s_productname = $("#s_productname").val();
                var s_productenname = $("#s_productenname").val();

                var s_create_time_begin = $("#s_create_time_begin").val();
                var s_create_time_end = $("#s_create_time_end").val();

                SYS.Core.ajax({
                    url: "data/productprize/list",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        productid: s_id || 0,
                        productname: s_productname,
                        productenname: s_productenname,
                        create_time_begin: s_create_time_begin,
                        create_time_end: s_create_time_end
                    },
                    success: function (data) {
                        var obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };

                        $("#myTable").bootstrapTable('destroy');
                        $('#myTable').bootstrapTable({
                            striped: true,
                            singleSelect: false,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination: 'server',
                            clickToSelect: true,
                            idField: 'id',
                            data: obj.data,
                            columns: [
                                {field: 'checked', checkbox: true} ,
                                {field: 'productid', title: '编号', align: 'center'},
                                {field: 'productname', title: '产品名称', align: 'center'},
                                {field: 'productenname', title: '产品英文名称', align: 'center'},
                                {field: 'pic', title: '封面', align: 'center',
                                    formatter:function (val,row,index){
                                        if(val && val != '') {
                                            if (val.indexOf("http") == -1) {
                                                return "<img src='https://xcx.championwei.cn/upload/admin/images/product/" + val + "' style='width:100px; height:50px;' />";
                                            } else {
                                                return "<img src='" + val + "' style='width:100px; height:50px;' />";
                                            }
                                        }
                                        return '-';
                                    }
                                },
                                {field: 'havenum', title: '剩余数量', align: 'center'},
                                {field: 'sendnum', title: '已送数量', align: 'center'},
                                {field: 'adddate', title: '日期', align: 'center'},
                                {field: 'sortnum', title: '排序号', align: 'center'},
                                {
                                    field: 'do', title: '操作', align: 'center',
                                    formatter: function (value, row, index) {
                                        var html = '';
                                        html += '<a href="javascript:void(0)" onclick="DATA.productprize.toEdit(' + row.productid + ')" class="btn btn-edit">编辑</a> | ';
                                        html += '<a href="javascript:void(0)" onclick="DATA.productprize.toRemove(' + row.productid + ')" class="btn btn-remove  ">删除</a>';
                                        return html;
                                    }
                                }
                            ],
                            onPageChange: function(number, size){
                                that.loadData(number, size);
                            },
                            onRefreshTable: function () {
                                that.loadData();
                            },
                            onClickCell: function (field, value, row, $element) {
                            }
                        });
                    }
                });
            },
            loadEvent: function () {
                var that = this;

                // 定义编辑框form
                var $form = $("#fm");

                // 查询
                $("#search-toolbar").on('click', "#btn_search", function () {
                    that.loadData();
                }).on("keydown ", "input", function (e) {
                    if (e.keyCode == 13) {
                        that.loadData();
                    }
                });

                // 初始化搜索日期控件
                SYS.Tool.initDaterangSearchWithHHmm('s_create_time', 's_create_time_begin', 's_create_time_end');

                //批量删除
                $("#btn_deletes").on('click',function(){
                    that.toRemoves();
                });

                // 绑定日期控件
                $("#adddate").datetimepicker({
                    minView: "hour",
                    format: 'yyyy-mm-dd hh:ii',
                    todayBtn: true,
                    language: 'zh-CN', // 汉化
                    autoclose: true    // 选择日期后自动关闭
                }).on('changeDate', function (ev) {
                    var field = $(this).attr("id");
                    $form.find("input[data-field='" + field + "']").val(ev.date.getTime());
                });

                // 保存新增
                $("#btn_contiune_add").on('click', function () {
                    // 不用关闭当前编辑框
                    that.save(1);
                });

                // 新增
                $("#btn_add").on('click', function () {
                    that.clearDatas();
                    // 初始化图片组件
                    that.initFileInput("pic", "hide_img");

                    $("#btn-add-div").show();
                    $("#btn-edit-div").hide();
                    that.showDiv('edit_div');
                });

                $("#btn_export").on('click', function () {
                    that.toExport();
                });

                $(".i-checks").iCheck({checkboxClass:"icheckbox_square-orange", radioClass:"iradio_square-orange"});

                // 返回
                $(".back_list").on('click', function () {
                    that.clearDatas();
                    that.showDiv('main_div');
                });

                //
                $('#fm').bootstrapValidator({
                    excluded: ':disabled',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        // title: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         }
                        //     }
                        // },
                        // order: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         },
                        //         regexp: {
                        //             regexp: /^[1-9]\d*$/i,
                        //             message: '格式不正确，必须大于0'
                        //         }
                        //     }
                        // }
                    }
                }).on('success.form.bv', function (e) {
                    e.preventDefault();

                    that.save(0);
                });

            },
            save: function (isContinus) {
                var that = this;

                var id = $("#_id").val();
                var productname = $("#productname").val();
                var productenname = $("#productenname").val();
                var pic = $("#hide_img").val();
                var havenum = $("#havenum").val();
                var sendnum = $("#sendnum").val();
                var adddate = $("#adddate").val();
                var sortnum = $("#sortnum").val();

                SYS.Core.ajax({
                    url: 'data/productprize/save',
                    common: {},
                    data:{
                        productid: id || 0,
                        productname: productname,
                        productenname: productenname,
                        pic: pic,
                        havenum: havenum,
                        sendnum: sendnum,
                        adddate: adddate,
                        sortnum: sortnum
                    },
                    success: function (data) {
                        if(data.code == 1) {
                            $.messager.popup(data.msg, 'success');

                            if (isContinus) {
                                that.clearDatas();
                                // 初始化图片组件
                                that.initFileInput("pic", "hide_img");

                                that.loadData();
                                that.showDiv('edit_div');
                            } else {
                                that.loadData();
                                that.showDiv('main_div');
                            }

                        } else {
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg, 'error');
                        }
                    }
                })
            },
            toEdit: function (id) {
                var that = this;
                that.clearDatas();
                $("#btn-add-div").hide();
                $("#btn-edit-div").show();

                SYS.Core.ajax({
                    url: 'data/productprize/detail',
                    common: {},
                    data: {
                        productid: id ? id : 0
                    },
                    success: function (data) {
                        if (data.code == 1) {
                            var obj = data.data;
                            const id = obj.productid;
                            const productname = obj.productname;
                            const productenname = obj.productenname;
                            const pic = obj.pic;


                            const havenum = obj.havenum;
                            const sendnum = obj.sendnum;
                            const adddate = obj.adddate;
                            const sortnum = obj.sortnum;

                            $("#_id").val(id);
                            $("#productname").val(productname);
                            $("#productenname").val(productenname);

                            var initialPreview_img = [];
                            if (pic) {
                                $("#hide_img").val(pic);
                                if (pic.indexOf("http") == -1) {
                                    initialPreview_img = ["<img src='https://xcx.championwei.cn/upload/admin/images/product/" + pic + "' class='file-preview-image'/>"];
                                } else {
                                    initialPreview_img = ["<img src='" + pic + "' class='file-preview-image'/>"];
                                }
                            }
                            that.initFileInput( "pic", "hide_img", initialPreview_img);

                            $("#havenum").val(havenum);
                            $("#sendnum").val(sendnum);
                            $("#adddate").val(adddate);

                            $("#sortnum").val(sortnum);

                            that.showDiv('edit_div');
                        }
                    }
                });
            },
            toRemove: function (id) {
                var that = this;
                $.messager.confirm("确定要删除吗？", function() {
                    SYS.Core.ajax({
                        url: "data/productprize/delete",
                        common: {},
                        data: {
                            ids: [id]
                        },
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup(data.msg, "success");
                                that.loadData();
                            }else{
                                $.messager.popup(data.msg,'error');
                            }
                        }
                    })
                });
            },
            toRemoves: function () {
                var that = this;
                var selRows = $('#myTable').bootstrapTable('getSelections');
                var delIds = [];
                if(selRows.length > 0){
                    $.each(selRows, function (i, obj) {
                        if(obj.id > 0){
                            delIds.push(obj.id);
                        }
                    });
                    $.messager.confirm("确定批量删除吗？", function() {
                        SYS.Core.ajax({
                            url: "data/productprize/delete",
                            common: {},
                            data: {
                                ids: delIds
                            },
                            success: function (data) {
                                if(data.code == 1){
                                    $.messager.popup(data.msg,"success");
                                    that.loadData();
                                }else{
                                    $.messager.popup(data.msg,'error');
                                }
                            }
                        })
                    });
                }else{
                    $.messager.popup('请选择一条记录后再删除','warn');
                }
            },
            initFileInput: function (imgId, imgHideId, initialPreview) {
                var options = {
                    img_id: imgId,
                    type_id: 3000,
                    initialPreview: initialPreview,
                    hid_img_id: imgHideId,
                    showZoom: false
                };
                SYS.Tool.initSingleImg(options);
            },
            showDiv: function (div) {
                var divs = ['main_div','edit_div','import_div'];
                for(var i=0; i<divs.length; i++){
                    $("#" + divs[i]).hide();
                }
                $("#" + div).show();
            }
        }
    });
    DATA.productprize.init();
});